﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NetCore.Enums;
using NetCore.ServiceGroup.Esign.HttpApis;
using NetCore.ServiceGroup.Esign.HttpDtos;
using System;

namespace NetCore
{
    /// <summary>
    /// E签初始化 IApplicationBuilder的静态扩展 仅提供给startup方法里面使用，故放在web模块
    /// </summary>
    public static class ESignApplicationBuilderExtensions
    {
        public static void InitESign(this IApplicationBuilder app)
        {
            var options = app.ApplicationServices.GetService<IOptions<ProjectConfigDto>>().Value;
            var signApi = app.ApplicationServices.GetService<IESignApi>();
            var signApiResult = signApi.Init(new InitInputDto
            {
                ProjectConfig = options,
                HttpConfig = new HttpConnectConfigDto
                {
                    HttpType = HttpTypes.HTTP,
                    Retry = 5,
                    ProxyIp = string.Empty,
                    ProxyPort = null,
                },
                SignConfig = new SignatureConfigDto
                {
                    AlgorithmType = AlgorithmType.HMAC_SHA256
                }
            }).InvokeAsync().Result;
            if (signApiResult.ErrCode != 0)
            {
                throw new Exception("E签宝初始化失败：" + signApiResult.Msg);
            }
        }
    }
}
